package com.wbao.dianniu.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.tencent.imsdk.TIMConversationType;
import com.tencent.qcloud.timchat.utils.ChatActivity;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.data.RecruitAddData;
import com.wbao.dianniu.data.RecruitListData;
import com.wbao.dianniu.listener.IJobDeliveryAddListener;
import com.wbao.dianniu.listener.IRecruitDelListener;
import com.wbao.dianniu.listener.IRecruitDetailsListener;
import com.wbao.dianniu.listener.IRecruitStatusListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.GlobalUserData;
import com.wbao.dianniu.manager.JobDeliveryAddManager;
import com.wbao.dianniu.manager.RecruitDelManager;
import com.wbao.dianniu.manager.RecruitDetailsManager;
import com.wbao.dianniu.update.RecruitListChangeManager;
import com.wbao.dianniu.update.RecruitListChangeManager.RecruitChangedListener;
import com.wbao.dianniu.manager.RecruitStatusManager;
import com.wbao.dianniu.update.ShareSDKManager;
import com.wbao.dianniu.update.ErrorDialogHelper;
import com.wbao.dianniu.utils.ActivityUtils;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PermissionUtils;
import com.wbao.dianniu.utils.ReportType;

/**
 * 岗位详情
 *
 * @author yejianjun
 */
public class RecruitDetailsActivity extends BaseActivity implements IRecruitDetailsListener, IJobDeliveryAddListener, IRecruitDelListener, IRecruitStatusListener, RecruitChangedListener {

    private LinearLayout waittingLayout;
    private ProgressBar waittingProBar;
    private TextView waittingTV;

    private RecruitDetailsManager manager;
    private JobDeliveryAddManager jdManager;
    private RecruitStatusManager statusManager;
    private RecruitDelManager delManger;
    private TextView tv_post;
    private TextView tv_salary;
    private TextView tv_tryout;
    private TextView tv_trial_ruel;
    private TextView tv_recruitCount;
    private TextView tv_address;
    private TextView tv_experience;
    private TextView tv_education;
    private TextView tv_describle;
    private int recruitId;
    private Button applyButton, sendmsgBtn, callBtn;
    private Dialog pDialog;
    private Button rightBtn;
    private Dialog dialog;
    private RecruitAddData data;
    private Button deleteBtn;
    private Button editBtn;
    private Button closeBtn;
    private RecruitListChangeManager recruitListChangeManager;
    private LinearLayout layout1, layout2;
    // 是否是倒入的数据
    private boolean isImport;
    private String mobile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_recruit_details, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        setTitleName(getResources().getString(R.string.position_details));
        initWattingView();
        init();
        manager = new RecruitDetailsManager(this);
        manager.addRecruitDetailsListener(this);
        jdManager = new JobDeliveryAddManager(this);
        jdManager.addJobDeliveryAddListener(this);
        statusManager = new RecruitStatusManager(this);
        statusManager.addRecruitStatusListener(this);
        delManger = new RecruitDelManager(this);
        delManger.addRecruitDelListener(this);
        recruitListChangeManager = RecruitListChangeManager.getInstance();
        recruitListChangeManager.addRecruitChangeListener(this);

        Intent intent = getIntent();
        String id = intent.getStringExtra(Const.INTENT_SCHEME_ID);
        if (null != id) {
            recruitId = Integer.valueOf(id);
        } else {
            recruitId = intent.getIntExtra(Const.INTENT_JOB_ID, 0);
        }
        manager.recruitDetails(recruitId, GlobalContext.getAccountId());
    }

    private void initWattingView() {
        waittingLayout = findViewById(R.id.waitting_layout);
        waittingProBar = findViewById(R.id.waitting_progress);
        waittingTV = findViewById(R.id.waitting_text_desc);
        waittingLayout.setVisibility(View.VISIBLE);
    }

    private void init() {
        tv_post = findViewById(R.id.recruit_detail_post);
        tv_tryout = findViewById(R.id.recruit_detail_trial);
        tv_trial_ruel = findViewById(R.id.recruit_detail_trial_ruel);
        tv_salary = findViewById(R.id.recruit_detail_salary);
        tv_address = findViewById(R.id.recruit_detail_address);
        tv_recruitCount = findViewById(R.id.recruit_detail_recruitCount);
        tv_experience = findViewById(R.id.recruit_detail_experience);
        tv_education = findViewById(R.id.recruit_detail_education);
        tv_describle = findViewById(R.id.recruit_detail_describe);
        Button btn_jubao = findViewById(R.id.recruit_detail_report);
        btn_jubao.setOnClickListener(this);
        applyButton = findViewById(R.id.recruit_detail_apply_job);
        sendmsgBtn = findViewById(R.id.recruit_detail_sendMsg);
        callBtn = findViewById(R.id.recruit_detail_call);
        closeBtn = findViewById(R.id.recruit_detail_close);
        editBtn = findViewById(R.id.recruit_detail_edit);
        deleteBtn = findViewById(R.id.recruit_detail_delete);
        layout1 = findViewById(R.id.recruit_detail_layout_1);
        layout2 = findViewById(R.id.recruit_detail_layout_2);
        applyButton.setOnClickListener(this);
        sendmsgBtn.setOnClickListener(this);
        callBtn.setOnClickListener(this);
        closeBtn.setOnClickListener(this);
        editBtn.setOnClickListener(this);
        deleteBtn.setOnClickListener(this);
        tv_trial_ruel.setOnClickListener(this);

        rightBtn = getRightTextButton();
        rightBtn.setText(getResources().getString(R.string.share));
        rightBtn.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                // 调用分享内容
                String imageUrl = GlobalContext.cdndownUrl + "logo.png";
                String content = "职位：" + data.getPost() + "\n" + "薪资：" + data.getSalary();
                ShareSDKManager shareSDKManager = ShareSDKManager.getInstance();
                shareSDKManager.showShare(RecruitDetailsActivity.this, content, 5, imageUrl, data.getId());
            }
        });

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.recruit_detail_report:    //举报
                ActivityUtils.intoReportActivity(RecruitDetailsActivity.this, ReportType.TYPE_RECRUIT, recruitId);
                break;
            case R.id.recruit_detail_apply_job:    //申请岗位
                if (!GlobalContext.getPerfectData()) {
                    ErrorDialogHelper.getInstance().showPerfectAuth(this);
                    return;
                }
                GlobalUserData userData = new GlobalUserData();
                if (!userData.getPerfectResume()) {
                    showJobAuth("您还未填写简历，是否现在完善！");
                    return;
                }
               /* pDialog = LoadingWaitDialog.createLoadingDialog(this, "");
                pDialog.show();*/
               // 申请前先弹出提示框
                applyRecruit(data);

                break;
            case R.id.recruit_detail_close:
                int st = 0;
                if (0 == data.getStatus()) {
                    st = 1;
                    showNotify(st, "当前已停止招聘，打开会启动招聘");
                } else {
                    st = 0;
                    showNotify(st, "当前正在招聘，关闭后会停止招聘");
                }
                break;
            case R.id.recruit_detail_edit:
                Intent editIntent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putInt(Const.BUNDLE_ID, data.getId());
                bundle.putString(Const.BUNDLE_POST, tv_post.getText().toString().trim());
                bundle.putString(Const.BUNDLE_SALARY, tv_salary.getText().toString().trim());
                bundle.putString(Const.BUNDLE_TRYOUT, tv_tryout.getText().toString().trim());
                bundle.putString(Const.BUNDLE_COUNT, tv_recruitCount.getText().toString().trim());
                bundle.putString(Const.BUNDLE_ADDRESS, tv_address.getText().toString().trim());
                bundle.putString(Const.BUNDLE_EXPERIENCE, tv_experience.getText().toString().trim());
                bundle.putString(Const.BUNDLE_EDUCATION, tv_education.getText().toString().trim());
                bundle.putString(Const.BUNDLE_DESCRIBLE, tv_describle.getText().toString().trim());
                editIntent.putExtra(Const.BUNDLE_EDIT, bundle);
                editIntent.setClass(this, RecruitReleaseActivity.class);
                startActivity(editIntent);
                break;
            case R.id.recruit_detail_delete:
                delDialog();
                break;
            /*case R.id.right_button:    //分享
                // 调用分享内容
                String imageUrl = GlobalContext.cdndownUrl + "logo.png";
                String content = "职位：" + data.getPost() + "\n" + "薪资：" + data.getSalary();
                ShareSDKManager shareSDKManager = ShareSDKManager.getInstance();
                shareSDKManager.showShare(this, content, 5, imageUrl, data.getId());
                break;*/
            case R.id.recruit_detail_trial_ruel:    //试用规则
                Intent intent = new Intent();
                intent.setClass(RecruitDetailsActivity.this, TrialRuelActivity.class);
                startActivity(intent);
                break;
            case R.id.recruit_detail_sendMsg:
                if (!GlobalContext.getPerfectData()) {
                    ErrorDialogHelper.getInstance().showPerfectAuth(this);
                    return;
                }
                int accountId = data.getAccountId();
                if (0 == accountId) {
                    Notification.toast(this, getResources().getString(R.string.recruit_detail_error));
                } else {
                    GlobalUserData globalUserData = new GlobalUserData();
                    if (null != data.getUserInfo()) {
                        ChatActivity.navToChat(this, globalUserData.getEnvironemt() + String.valueOf(accountId), TIMConversationType.C2C,GlobalContext.cdndownUrl +  data.getUserInfo().headPic, data.getUserInfo().realName, GlobalContext.cdndownUrl + GlobalContext.getHeadPic());
                    }
                }
                break;
            case R.id.recruit_detail_call:
                if (TextUtils.isEmpty(mobile)) {
                    if (!TextUtils.isEmpty(data.getUserInfo().mobile)) {
                        callDialog(data.getUserInfo().mobile);
                    } else {
                        Notification.toast(this, "手机号为空");
                    }
                } else {
                    callDialog(mobile);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 拨打电话
     */
    private void callDialog(final String phone) {
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle(phone);
        builder.setPositiveButton("呼叫", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                PermissionUtils.getInstance().intentToCall(RecruitDetailsActivity.this, phone);
            }
        });
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.create().show();
    }


    private void applyRecruit(final RecruitAddData recruitAddData){
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle("确认申请该岗位吗？");
        builder.setPositiveButton(getResources().getString(R.string.confirm), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
               jdManager.jobDeliveryAdd(GlobalContext.getAccountId(), recruitId, recruitAddData.getPost(), recruitAddData.getAccountId());
            }
        });
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.create().show();

    }

    /**
     * 显示完善简历弹出框
     */
    private void showJobAuth(String msg) {
        dialog = new Dialog(this, R.style.custom_Dialog);
        Window win = dialog.getWindow();
        win.getDecorView().setPadding(3, 3, 3, 3);
        win.setGravity(Gravity.CENTER);
        View view = LayoutInflater.from(this).inflate(R.layout.custom_message_dialog, null);
        Button okBtn = view.findViewById(R.id.custom_msg_ok);
        Button cancelBtn = view.findViewById(R.id.custom_msg_cancel);
        TextView message = view.findViewById(R.id.custom_msg_message);
        message.setText(msg);
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.show();
        okBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                // 跳转到编辑简历界面
                Intent intent = new Intent();
                intent.setClass(RecruitDetailsActivity.this, JobEditActivity.class);
                startActivity(intent);
            }
        });
        cancelBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
    }
    /**
     * 显示认证弹出框
     */
//	private void showDialog() {
//		dialog = new Dialog(this, R.style.custom_Dialog);
//		Window win = dialog.getWindow();
//		win.getDecorView().setPadding(3, 3, 3, 3);
//		win.setGravity(Gravity.BOTTOM);
//		View view = LayoutInflater.from(this).inflate(R.layout.jobrecruit_addlist_dialog, null);
//		Button applyBtn = (Button) view.findViewById(R.id.apply_job_recruit_list);
//		Button cancelBtn = (Button) view.findViewById(R.id.cancel);
//		//申请用户列表
//		applyBtn.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				if(null != dialog && dialog.isShowing()){
//					dialog.dismiss();
//				}
//				Intent intent = new  Intent();
//				intent.putExtra(GlobalContext.INTENT_REPORT_OBJECTID, recruitId);
//				intent.putExtra(GlobalContext.INTENT_REPORT_TYPE, 1);
//				intent.setClass(RecruitDetailsActivity.this, JobRecruitAddListActivity.class);
//				startActivity(intent);	
//			}
//		});
//		
//		// 取消
//		cancelBtn.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				if(null != dialog && dialog.isShowing()){
//					dialog.dismiss();
//				}
//			}
//		});
//		dialog.setContentView(view);
//		dialog.setCancelable(true);
//		dialog.show();
//	}

    /**
     * 删除求职对话框
     */
    private void delDialog() {
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle("确认删除本条招聘吗？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                //设置你的操作事项  
                delManger.jobRecruitDel(GlobalContext.getAccountId(), recruitId);
            }
        });
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.create().show();
    }

    @Override
    public void onRecruitDetailsFailure(int errorCode, String errorMsg) {
        waittingLayout.setVisibility(View.VISIBLE);
        waittingProBar.setVisibility(View.GONE);
        waittingTV.setText(errorMsg == null ? "" : errorMsg);
    }

    @Override
    public void onRecruitDetailsSuccess(RecruitAddData data) {
        if (null == data) {
            waittingLayout.setVisibility(View.VISIBLE);
            waittingProBar.setVisibility(View.GONE);
            waittingTV.setText("数据为空...");
            return;
        }
        waittingLayout.setVisibility(View.GONE);
//		rightImageBtn.setVisibility(View.VISIBLE);
        this.data = data;
        display(data);
    }

    private void display(RecruitAddData data) {
        tv_post.setText(data.getPost() == null ? "" : data.getPost());
        tv_tryout.setText(data.getTryout() == null ? "" : data.getTryout());
        tv_salary.setText(data.getSalary() == null ? "" : data.getSalary());
        tv_address.setText(data.getAddress() == null ? "" : data.getAddress());
        tv_recruitCount.setText(data.getRecruitCount() == null ? "" : data.getRecruitCount());
        tv_experience.setText(data.getExperience() == null ? "" : data.getExperience());
        tv_education.setText(data.getEducation() == null ? "" : data.getEducation());
        tv_describle.setText(data.getDescribe() == null ? "" : data.getDescribe());
        if (data.getAccountId() == GlobalContext.getAccountId()) {// 本人查看详情
            switchStatus(true);
            if (1 == data.getStatus()) {
                closeBtn.setText("关闭");
            } else {
                closeBtn.setText("打开");
            }
        } else {
            switchStatus(false);
            if (1 == data.getStatus()) {
                if (0 == data.getDeliverStatus()) {
                    applyButton.setText(getResources().getString(R.string.apply_jobs));
                    applyButton.setClickable(true);
                } else {
                    applyButton.setText(getResources().getString(R.string.has_delivered));
                    applyButton.setBackgroundColor(getResources().getColor(R.color.remark_gray_bg));
                    applyButton.setClickable(false);
                }
            } else {
                applyButton.setText(data.getStatusDesc() == null ? "" : data.getStatusDesc());
                applyButton.setBackgroundColor(getResources().getColor(R.color.remark_gray_bg));
                applyButton.setClickable(false);
            }

        }

        if (null != data.getUserInfo()) {
            sendmsgBtn.setBackgroundColor(getResources().getColor(R.color.title_bg));
            sendmsgBtn.setClickable(true);
        } else {    // 导入的数据 咨询和申请岗位 都不允许点击
            sendmsgBtn.setBackgroundColor(getResources().getColor(R.color.remark_gray_bg));
            sendmsgBtn.setClickable(false);
            applyButton.setBackgroundColor(getResources().getColor(R.color.remark_gray_bg));
            applyButton.setClickable(false);
        }

        if (!TextUtils.isEmpty(data.getMobile())) {
            mobile = data.getMobile();
            callBtn.setBackgroundColor(getResources().getColor(R.color.title_bg));
            callBtn.setClickable(true);
        } else if (null != data.getUserInfo()) {
            mobile = data.getUserInfo().mobile;
            callBtn.setBackgroundColor(getResources().getColor(R.color.title_bg));
            callBtn.setClickable(true);
        } else {
            callBtn.setBackgroundColor(getResources().getColor(R.color.remark_gray_bg));
            callBtn.setClickable(false);
        }

    }

    @Override
    public void onRecruitDelFailure(int errorCode, String errorMsg) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onRecruitDelSuccess() {
        recruitListChangeManager.notifyRemove(recruitId);
        Notification.toast(this, "已删除");
        finish();
    }

    @Override
    public void onRecruitStatusFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onRecruitStatusSuccess() {
        if (0 == data.getStatus()) {
            data.setStatus(1);
            closeBtn.setText("关闭");
        } else {
            data.setStatus(0);
            closeBtn.setText("打开");
        }
        RecruitManagerActivity.StatusChange(data.getId(), data.getStatus());
    }

    @Override
    public void onJobDeliveryAddFailure(int errorCode, String errorMsg) {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        Notification.toast(this, errorMsg == null ? "" : errorMsg);
    }

    @Override
    public void onJobDeliveryAddSuccess() {
        // TODO Auto-generated method stub
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        applyButton.setText(getResources().getString(R.string.has_delivered));
        applyButton.setBackgroundColor(getResources().getColor(R.color.remark_gray_bg));
        applyButton.setClickable(false);
        deliveredSuccess(RecruitDetailsActivity.this);
    }


    private void deliveredSuccess(final Context context) {
        CustomDialog.Builder build = new CustomDialog.Builder(RecruitDetailsActivity.this);
        build.setTitle(getResources().getString(R.string.job_delivered));
        build.setPositiveButton(this.getResources().getString(R.string.confirm),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        build.create().show();
    }


    @Override
    public void recruitAddChanged(RecruitListData data) {

    }

    @Override
    public void recruitRemoveChanged(int position) {

    }

    @Override
    public void recruitModifyChanged(int id, RecruitAddData data) {
        display(data);
    }

    private void showNotify(final int status, String msg) {
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle(msg);
        builder.setPositiveButton(getResources().getString(R.string.confirm),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        statusManager.recruitStatus(GlobalContext.getAccountId(), recruitId, status);
                    }
                });
        builder.setNegativeButton(getResources().getString(R.string.cancel),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.create().show();
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != recruitListChangeManager) {
            recruitListChangeManager.removeRecruitChangeListener(this);
        }
        if (null != manager) {
            manager.removeRecruitDetailsListener(this);
        }
        if (null != jdManager) {
            jdManager.removeJobDeliveryAddListener(this);
        }
        if (null != statusManager) {
            statusManager.removeRecruitStatusListener(this);
        }
        if (null != delManger) {
            delManger.removeJRecruitDelListener(this);
        }
    }

    private void switchStatus(boolean isSelf) {
        if (isSelf) {
            layout1.setVisibility(View.GONE);
            layout2.setVisibility(View.VISIBLE);
        } else {
            layout1.setVisibility(View.VISIBLE);
            layout2.setVisibility(View.GONE);
        }
    }


}
